import { Card, Table, Image, Tag, Space, Button, Popconfirm } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { useHistory } from 'react-router-dom'
import { COLORS, STATUS } from '@/constants'
import defaultImg from '@/assets/error.png'
import { columns } from './table'

function MyTable (props) {
  const history = useHistory()
  // 拿到父组件数据
  let { pageSize, current, total } = props.paging
  let { onChange, del } = props.fn
  let articleList = props.article

  // 设置行内渲染组件 
  columns.forEach(item => {
    if (item.title === '封面') {
      item.render = cover => {
        // 加载失败显示图像占位符。
        // src='error'设置图片加载失败   fallback 设置占位图像
        if (cover.type === 0)
          return (
            <Image
              width={100}
              height={100}
              src='error'
              fallback={defaultImg}
            ></Image>
          )
        return (
          <Image
            width={100}
            height={100}
            src={cover.images[0]}
            fallback={defaultImg}
          ></Image>
        )
      }
    } else if (item.title === '状态') {
      item.render = status => {
        return <Tag color={COLORS[status]}>{STATUS[status]}</Tag>
      }
    } else if (item.title === '操作') {
      item.render = id => {
        return (
          <Space size='small'>
            <Button
              onClick={() => history.push('/home/publish?id=' + id)}
              type='primary'
              shape='circle'
              icon={<EditOutlined />}
            />
            <Popconfirm title='确定要删除该文章吗？' onConfirm={() => del(id)}>
              <Button
                type='primary'
                shape='circle'
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  })
  return (
    <Card
      title={`根据筛选条件共查询到${props.total}条结果:`}
      style={{ marginTop: 10 }}
    >
      <Table
        rowKey='id'
        dataSource={articleList}
        columns={columns}
        pagination={{ pageSize, current, total, onChange }}
      />
    </Card>
  )
}

export default MyTable
